<!--
 * @Description: 
 * @Author: mxy
 * @Date: 2022-11-14 19:44:06
 * @LastEditors: mxy
 * @LastEditTime: 2022-11-14 20:05:52
-->
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script src="./axios.js"></script>
    <script>
        function ajax({ method, url, params, data }) {
            return new Promise((resolve, reject) => {
                const xhr = new XMLHttpRequest()
                xhr.addEventListener('load', function () {
                    if (xhr.status >= 200 && xhr.status < 300) {
                        resolve(JSON.parse(xhr.response))
                    } else if (xhr.status >= 300) {
                        reject(JSON.parse(xhr.response))
                    }
                })
                let arr = []
                for (let k in params) {
                    arr.push(`${k}=${params[k]}`)
                }
                xhr.open(method, `${url}?${arr.join('&')}`)
                if (data instanceof FormData) {
                    xhr.send()
                } else if (data instanceof Object) {
                    xhr.setRequestHeader('Content-Type', 'application/json')
                    xhr.send(JSON.stringify(data))
                } else if (typeof data === "string") {
                    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
                    xhr.send(data)
                } else {
                    xhr.send()
                }

            })
        }
        ajax({
            method: 'get',
            url: 'http://www.itcbc.com:3006/api/getbooks',
            params: {
                appkey: 'xiaomeng'
            }
        }).then(res => {
            console.log(res)
        })

        ajax({
            method: 'post',
            url: 'http://www.itcbc.com:3006/api/addbook',
            data: {
                bookname: '11',
                author: '11',
                publisher: '11',
                appkey: 'xiaomeng',
            }
        }).then(res => {
            console.log(res)
        })
    </script>
</body>

</html>